const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    trainId: '',
    trainPrograms: [],
    courseName: '',
    traineePhone: null,
    isFatLoss: false,
    finishTrain: false,
    emsRanges: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    weightRanges: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 90, 100],
    timesRanges: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
    secondRanges: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
    positions: [{
      position: '二头',
      columnName: 'ertou',
      ertou1: 0,
      ertou2: 0
    }, {
      position: '背阔',
      columnName: 'beikuo',
      beikuo1: 0,
      beikuo2: 0
    }, {
      position: '三头',
      columnName: 'santou',
      santou1: 0,
      santou2: 0
    }, {
      position: '下背',
      columnName: 'xiabei',
      xiabei1: 0,
      xiabei2: 0
    }, {
      position: '胸部',
      columnName: 'xiongbu',
      xiongbu1: 0,
      xiongbu2: 0
    }, {
      position: '臀部',
      columnName: 'tunbu',
      tunbu1: 0,
      tunbu2: 0
    }, {
      position: '腹部',
      columnName: 'fubu',
      fubu1: 0,
      fubu2: 0
    }, {
      position: '前腿',
      columnName: 'qiantui',
      qiantui1: 0,
      qiantui12: 0
    }, {
      position: '上背',
      columnName: 'shangbei',
      shangbei1: 0,
      shangbei2: 0
    }, {
      position: '后腿',
      columnName: 'houtui',
      houtui1: 0,
      houtui2: 0
    }]
  },

  findModeItems: function(strongOption) {
    const name = this.data.courseName;
    const positionTrains = app.globalData.positionTrains;
    const size = positionTrains.length;
    for (let i = 0; i < size; i++) {
      const positionTrain = positionTrains[i];
      if (positionTrain.name === name) {
        if ('NORMAL' === strongOption) {
          return positionTrain.normal;
        } else if ('ADVANCE' === strongOption) {
          return positionTrain.advance;
        } else if ('CHALLENGE' === strongOption) {
          return positionTrain.challenge;
        }
      }
    }
    return [];
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    const trainId = wx.getStorageSync('courseId');
    const traineePhone = wx.getStorageSync('traineePhone');
    const courseName = wx.getStorageSync("courseName");
    if (courseName === '减脂训练') {
      this.setData({
        isFatLoss: true,
        traineePhone
      });
    }
    const finishTrain = wx.getStorageSync("finishTrain");
    wx.setNavigationBarTitle({
      title: courseName
    });
    that.setData({
      trainId,
      courseName,
      finishTrain
    });
    that.fetchData();
    that.fetchEms(traineePhone);
  },
  fetchData: function() {
    const that = this;
    const trainId = this.data.trainId;
    const url = app.globalData.url;
    wx.request({
      url: url + '/train/getCourseProgram/' + trainId,
      success: function(response) {
        if (response.data.success) {
          const content = response.data.content;
          that.setData({
            trainPrograms: content
          });
        } else {
          wx.showToast({
            title: '获取训练项目出错',
            icon: 'none'
          })
        }
      }
    })
  },
  fetchEms: function(traineePhone) {
    const url = app.globalData.url;
    const positions = this.data.positions;
    const that = this;
    wx.request({
      url: url + '/train/emsAssessment/' + traineePhone,
      success: function(response) {
        if (response.data.success) {
          const emsObj = response.data.content;
          positions.forEach(function(position) {
            switch (position.columnName) {
              case 'ertou':
                position.ertou1 = emsObj.ertou1;
                position.ertou2 = emsObj.ertou2;
                break;
              case 'santou':
                position.santou1 = emsObj.santou1;
                position.santou2 = emsObj.santou2;
                break;
              case 'xiongbu':
                position.xiongbu1 = emsObj.xiongbu1;
                position.xiongbu2 = emsObj.xiongbu2;
                break;
              case 'fubu':
                position.fubu1 = emsObj.fubu1;
                position.fubu2 = emsObj.fubu2;
                break;
              case 'shangbei':
                position.shangbei1 = emsObj.shangbei1;
                position.shangbei2 = emsObj.shangbei2;
                break;
              case 'beikuo':
                position.beikuo1 = emsObj.beikuo1;
                position.beikuo2 = emsObj.beikuo2;
                break;
              case 'xiabei':
                position.xiabei1 = emsObj.xiabei1;
                position.xiabei2 = emsObj.xiabei2;
                break;
              case 'tunbu':
                position.tunbu1 = emsObj.tunbu1;
                position.tunbu2 = emsObj.tunbu2;
                break;
              case 'qiantui':
                position.qiantui1 = emsObj.qiantui1;
                position.qiantui2 = emsObj.qiantui2;
                break;
              case 'houtui':
                position.houtui1 = emsObj.houtui1;
                position.houtui2 = emsObj.houtui2;
                break;
            }
          });
          that.setData({
            positions
          });
        }
      }
    });
  },
  addGroup: function(e) {
    const programId = e.currentTarget.dataset.id;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        if (!program.groups) {
          program.groups = [];
        }
        program.groups.push({
          id: Math.random(),
          weight: 0,
          group: 0,
          second: 0
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  getEmsValue: function(position) {
    const positions = this.data.positions;
    const size = positions.length;
    for (let i = 0; i < size; i++) {
      const selectPosition = positions[i];
      if (position === selectPosition.position) {
        return selectPosition[selectPosition.columnName + '1'];
      }
    }
  },
  changeMode: function(e) {
    const that = this;
    const strongOption = e.currentTarget.dataset.value;
    const programId = e.currentTarget.dataset.id;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.strongOption = strongOption;
        const modeItems = that.findModeItems(strongOption);
        program.items = [];
        modeItems.forEach(function(item) {
          const emsValue = that.getEmsValue(item) || 0;
          program.items.push({
            position: item,
            strongValue: emsValue
          });
        });
        program.groups = [];
        program.groups.push({
          id: Math.random(),
          weight: 0,
          group: 0,
          second: 0
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  removeGroup: function(e) {
    const that = this;
    const programId = e.currentTarget.dataset.program;
    const groupId = e.currentTarget.dataset.id;
    const trainPrograms = this.data.trainPrograms;
    wx.showModal({
      title: '提示',
      content: '确定删除此行？',
      success(res) {
        if (res.confirm) {
          trainPrograms.forEach(function(program) {
            if (program.id === programId) {
              if (program.groups.length <= 1) {
                wx.showToast({
                  title: '至少留有一组训练',
                  icon: 'none'
                });
              } else {
                const newArr = program.groups.filter(function(item) {
                  return item.id !== groupId;
                });
                program.groups = newArr;
              }
            }
          });
          that.setData({
            trainPrograms
          });
        }
      }
    })
  },
  bindWeight: function(e) {
    const programId = e.currentTarget.dataset.program;
    const groupId = e.currentTarget.dataset.id;
    // const index = e.detail.value;
    // const weightRanges = this.data.weightRanges;
    // const trainPrograms = this.data.trainPrograms;
    // trainPrograms.forEach(function(program) {
    //   if (program.id === programId) {
    //     program.groups.forEach(function(item) {
    //       if (item.id === groupId) {
    //         item.weight = weightRanges[index];
    //       }
    //     });
    //   }
    // });
    const value = e.detail.value;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.groups.forEach(function(item) {
          if (item.id === groupId) {
            item.weight = value;
          }
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  bindGroup: function(e) {
    const programId = e.currentTarget.dataset.program;
    const groupId = e.currentTarget.dataset.id;
    // const index = e.detail.value;
    // const timesRanges = this.data.timesRanges;
    // const trainPrograms = this.data.trainPrograms;
    // trainPrograms.forEach(function(program) {
    //   if (program.id === programId) {
    //     program.groups.forEach(function(item) {
    //       if (item.id === groupId) {
    //         item.group = timesRanges[index];
    //       }
    //     });
    //   }
    // });
    const value = e.detail.value;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.groups.forEach(function(item) {
          if (item.id === groupId) {
            item.group = value;
          }
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  bindWholeStrong: function(e) {
    const programId = e.currentTarget.dataset.program;
    const index = e.detail.value;
    const emsRanges = this.data.emsRanges;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.emsWholeStrength = emsRanges[index];
      }
    });
    this.setData({
      trainPrograms
    });
  },
  bindSecond: function(e) {
    const programId = e.currentTarget.dataset.program;
    const groupId = e.currentTarget.dataset.id;
    const index = e.detail.value;
    const secondRanges = this.data.secondRanges;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.groups.forEach(function(item) {
          if (item.id === groupId) {
            item.second = secondRanges[index];
          }
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  bindInputStrong: function(e) {
    const programId = e.currentTarget.dataset.program;
    const position = e.currentTarget.dataset.position;
    const index = e.detail.value;
    const emsRanges = this.data.emsRanges;
    const trainPrograms = this.data.trainPrograms;
    trainPrograms.forEach(function(program) {
      if (program.id === programId) {
        program.items.forEach(function(item) {
          if (item.position === position) {
            item.strongValue = emsRanges[index];
          }
        });
      }
    });
    this.setData({
      trainPrograms
    });
  },
  addMovement: function() {
    const courseName = this.data.courseName;
    wx.setStorageSync('courseName', courseName);
    wx.setStorageSync('positions', JSON.stringify(this.data.positions));
    wx.navigateTo({
      url: '/pages/movementSelection/movementSelection'
    })
  },
  showOperation: function(e) {
    const programId = e.currentTarget.dataset.id;
    const that = this;
    wx.showActionSheet({
      itemList: ['删除此训练项目'],
      success(res) {
        if (res.tapIndex == 0) {
          that.deleteProgram(programId);
        }
      }
    })
  },
  deleteProgram: function(programId) {
    const that = this;
    const url = app.globalData.url;
    wx.request({
      url: url + '/train/deleteProgram/' + programId,
      success: function(response) {
        if (response.data.success) {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          that.fetchData();
        } else {
          wx.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    });
  },
  saveProgram: function() {
    const url = app.globalData.url;
    const trainId = this.data.trainId;
    const trainPrograms = this.data.trainPrograms;
    wx.request({
      url: url + '/train/savePrograms',
      data: {
        trainId,
        trainPrograms
      },
      method: 'POST',
      success: function(response) {
        if (response.data.success) {
          wx.navigateBack({
            delta: 1
          });
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: response.data.message || '保存失败',
            icon: 'none'
          })
        }
      }
    })
  }
})